package com.webside.points.wechat;

import java.security.MessageDigest;

/*
 * SHA1 算法
 */
public class SHA1Util {

	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * SHA1编码
	 * 
	 * @param origin  原始字符串
	 * @return 经过SHA1加密之后的结果
	 */
	public static String SHA1Encode(String origin) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(origin.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}

	public static void main(String[] args) {
		try {
			String s = "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VPKsUUDCBdAabvCmKaetXKq2P9fPL9AWU8fJgvHK2Fv0q3Ta8uFt7-Qu3ETxlnA7Ug&noncestr=nkpjpaxhbazb21mh&timestamp=1465451855&url=http://www.aifresh.com/getAccessToken";
			System.out.println(SHA1Util.SHA1Encode(s));
			System.out.println(Long.toString(System.currentTimeMillis() / 1000));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}